package com.biz.primus.management.homepage.controller;

import com.biz.primus.common.utils.JsonUtils;
import com.biz.primus.homepage.vo.*;
import com.biz.primus.management.base.controller.AbstractBaseController;
import com.biz.primus.management.homepage.feign.HomepageFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

import static org.apache.commons.lang.StringUtils.isNotBlank;

/**
 * @author jiangnan
 * @Description:
 */
@Slf4j
@Controller
@RequestMapping("management/homepage")
@Secured("ROLE_HOMEPAGE")
public class HomepageController extends AbstractBaseController {


    private final HomepageFeignClient homepageFeignClient;

    public HomepageController(HomepageFeignClient homepageFeignClient) {
        this.homepageFeignClient = homepageFeignClient;
    }

    @GetMapping
    @PreAuthorize("hasAuthority('OPT_HOMEPAGE_LIST')")
    @ResponseBody
    public ModelAndView list() {
        List<CoverRoVo> covers = homepageFeignClient.listCover();
        return new ModelAndView("cover/list").addObject("covers", covers);
    }

    @RequestMapping(value = "new", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('OPT_HOMEPAGE_CREATE')")
    public ModelAndView forwardToNewPage() {

        return new ModelAndView("cover/edit");
    }

    @RequestMapping(method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('OPT_HOMEPAGE_EDIT')")
    @ResponseBody
    public String save(CoverUpdateVo coverUpdateVo) {

        CoverUpdateVo savedCover = homepageFeignClient.saveCover(coverUpdateVo);
        return String.valueOf(savedCover.getId());
    }

    @RequestMapping(value = "{coverId}", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('OPT_HOMEPAGE_EDIT')")
    public ModelAndView forwardToEditPage(@PathVariable(value = "coverId") String coverId) {
        CoverRoVo cover = homepageFeignClient.findCover(coverId);
        List<ProgramRoVo> programs = homepageFeignClient.getAllProgramsByCoverId(coverId);
        return new ModelAndView("cover/edit").addObject("cover", cover).addObject("programs", programs);
    }

    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('OPT_HOMEPAGE_DELETE')")
    public void delete(CoverDeleteVo coverDeleteVo) {

        homepageFeignClient.deleteCover(coverDeleteVo);
    }

    @RequestMapping(value = "{coverId}/preview", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('OPT_COVER_LIST')")
    public String preview(HttpServletResponse response, @PathVariable String coverId)
            throws IOException {

        if (coverId != null) {
            CoverRoVo coverRo = homepageFeignClient.findCover(coverId);
            Boolean disableCache = true;
            String homepageContent = "";
//                    homepageFeignClient.getHomePageHtmlContentByCover(coverRo, disableCache);
            response.setContentType("text/html");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(homepageContent);
        }
        return null;
    }

    @RequestMapping(value = "{coverId}/programs/new", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('OPT_HOMEPAGE_EDIT')")
    public ModelAndView forwardToProgramNewPage(@PathVariable(value = "coverId") String coverId, @RequestParam(value = "parentId", required = false) Long parentId) {

        CoverRoVo cover = homepageFeignClient.findCover(coverId);
        ProgramRoVo parent = homepageFeignClient.findProgram(parentId);
        return new ModelAndView("cover/editProgram").addObject("cover", cover).addObject("parent",
                parent).addObject("elementDataProviders", homepageFeignClient.listCoverProvider());
    }

    @RequestMapping(value = "{coverId}/programs/{programId}", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('OPT_HOMEPAGE_EDIT')")
    public ModelAndView forwardToProgramEditPage(@PathVariable(value = "coverId") String coverId, @PathVariable(value = "programId") Long programId) {

        CoverRoVo cover = homepageFeignClient.findCover(coverId);
        ProgramDetailRespVo programDetail = homepageFeignClient.getProgramDetail(programId);
        ProgramRoVo parent = null;
        if (programDetail != null && programDetail.getProgram() != null) {
            parent = homepageFeignClient.findProgram(programDetail.getProgram().getParentId());
        }
        return new ModelAndView("cover/editProgram").addObject("cover", cover).addObject("programDetail", programDetail).addObject("parent", parent).addObject("elementDataProviders", homepageFeignClient.listCoverProvider());
    }

    @RequestMapping(value = "{coverId}/programs", method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('OPT_HOMEPAGE_EDIT')")
    @ResponseBody
    public String updateProgram(@PathVariable(value = "coverId") String coverId, ProgramUpdateReqVo reqVo) {

        CoverRoVo cover = homepageFeignClient.findCover(coverId);
        ProgramRoVo programRo = homepageFeignClient.save(reqVo);
        return programRo.getId().toString();
    }

    @RequestMapping(value = "{coverId}/programs/delete", method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('OPT_HOMEPAGE_DELETE')")
    public void deleteProgram(@PathVariable(value = "coverId") String coverId, @RequestParam("programId") Long programId) {

        homepageFeignClient.delete(programId);
    }

    @RequestMapping(value = "programs/elements", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('OPT_HOMEPAGE_EDIT')")
    public ModelAndView forwardToCoverTemplateDataElementEditPage(@RequestParam(value = "index", required = false) Integer index) {

        return new ModelAndView("cover/coverTemplateDataElement").addObject("index", index);
    }

    @RequestMapping(value = "{coverId}/clone", method = RequestMethod.GET)
    @ResponseBody
    @PreAuthorize("hasAuthority('OPT_HOMEPAGE_CLONE')")
    public CoverWithPrograms coverClone(@PathVariable String coverId) {

        log.debug("Received GET request '/covers/{}/clone' request.", coverId);
        return homepageFeignClient.clone(coverId);
    }

    @RequestMapping(value = "clone", method = RequestMethod.POST)
    @ResponseBody
    @PreAuthorize("hasAuthority('OPT_HOMEPAGE_CLONE')")
    public String cloneCover(String coverJson) {
        log.debug("Received GET request '/covers/clone' request with coverJson:{}.", coverJson);
        CoverRoVo newCoverRo = null;
        if (isNotBlank(coverJson)) {
            CoverWithPrograms coverWithPrograms = JsonUtils.json2Obj(coverJson, CoverWithPrograms.class);
            newCoverRo = homepageFeignClient.doClone(coverWithPrograms, "待设置");
        }
        return newCoverRo == null ? null : newCoverRo.getId();
    }

}
